<template>
<div>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
     v-dialogDrag
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <!-- <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="商家角色（0：平台，1：房产中介，2：楼盘，3：4S店，4：汽贸店，5：招聘企业）" prop="activityRole"
                :rules="[
                  {required: true, message:'商家角色（0：平台，1：房产中介，2：楼盘，3：4S店，4：汽贸店，5：招聘企业）不能为空', trigger:'blur'}
                 ]">
                    <el-radio-group v-model="inputForm.activityRole">
                        <el-radio v-for="item in $dictUtils.getDictList('')" :label="item.value" :key="item.id">{{item.label}}</el-radio>
                    </el-radio-group>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="角色关联ID" prop="roleAssociationId"
                :rules="[
                  {required: true, message:'角色关联ID不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.roleAssociationId" placeholder="请填写角色关联ID"     ></el-input>
           </el-form-item>
        </el-col> -->
        <el-col :span="12">
            <el-form-item label="用户" prop="user.id"
                :rules="[
                  {required: true, message:'用户不能为空', trigger:'blur'}
                 ]">
          <GridSelect
            title="选择用户"
            labelName = 'phone'
            labelValue = 'id'
            :value = "inputForm.user.id"
            :limit="1"
            @getValue='(value,item) => {inputForm.user.id=value,inputForm.name=item[0].shop.shopName,inputForm.address=item[0].shop.shopAddress,inputForm.longitude=item[0].shop.longitude,inputForm.latitude=item[0].shop.latitude}'
            :columns="[
            {
              prop: 'id',
              label: '主键'
            },
            {
              prop: 'phone',
              label: '手机号(账号唯一)'
            },
            {
              prop: 'image',
              label: '头像'
            },
            {
              prop: 'nikeName',
              label: '昵称'
            }
            ]"
            :searchs="[
            {
              prop: 'phone',
              label: '手机号(账号唯一)'
            },
            {
              prop: 'nikeName',
              label: '昵称'
            }
            ]"
            dataListUrl="/userinfo/tUserInfo/list?isEnable=1&delFlags=0"
            entityBeanName="tUserInfo"
            queryEntityUrl="/userinfo/tUserInfo/queryById">
          </GridSelect>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="商家名称" prop="name"
                :rules="[
                 ]">
              <el-input v-model="inputForm.name" placeholder="请填写商家名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="商家图片" prop="picture"
                :rules="[
                 ]">
              <el-upload ref="picture"
              v-if="visible"
              list-type="picture-card"
                    :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/common_eventmerchants/commonEventMerchants`"
                    :headers="{token: $cookie.get('token')}"
                    :on-preview="(file, fileList) => {
                        $alert(`<img style='width:100%' src=' ${(file.response && file.response.url) || file.url}'/>`,  {
                          dangerouslyUseHTMLString: true,
                          showConfirmButton: false,
                          closeOnClickModal: true,
                          customClass: 'showPic'
                        });
                    }"
                    :on-success="(response, file, fileList) => {
                       inputForm.picture = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
                    }"
                    :on-remove="(file, fileList) => {
                      $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
                        $message.success(data.msg)
                      })
                      inputForm.picture = fileList.map(item => item.url).join('|')
                    }"
                    :before-remove="(file, fileList) => {
                      return $confirm(`确定移除 ${file.name}？`)
                    }"
                    multiple
                    :limit="1"
                    :on-exceed="(files, fileList) =>{
                      $message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
                    }"
                    :file-list="pictureArra">
                    <i class="el-icon-plus"></i>
                  </el-upload>
           </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="商家地址" prop="address"
                :rules="[
                 ]">
              <el-input v-model="inputForm.address" 
                 ref="handleinput"
                  id="handleinput"
               placeholder="请填写商家地址"     ></el-input>
           </el-form-item>
        </el-col>

        <el-col :span="12">
            <el-form-item label="商家经度" prop="longitude"
                :rules="[
                 ]">
              <el-input v-model="inputForm.longitude" placeholder="请填写商家经度" disabled  ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="商家纬度" prop="latitude"
                :rules="[
                 ]">
              <el-input v-model="inputForm.latitude" placeholder="请填写商家纬度"   disabled  ></el-input>
           </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="地图" prop="">
            <div ref="container" id="containepic"></div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks"
                :rules="[
                 ]">
          <el-input type="textarea" v-model="inputForm.remarks" placeholder="请填写备注信息"     ></el-input>
           </el-form-item>
        </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import GridSelect from '@/components/gridSelect'
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        pictureArra: [],
        inputForm: {
          id: '',
          activityRole: '',
          roleAssociationId: '',
          user: {
            id: ''
          },
          name: '',
          picture: '',
          address: '',
          longitude: '',
          latitude: '',
          remarks: ''
        },
        markersArray: [],
      }
    },
    components: {
      GridSelect
    },
    methods: {
      init (method, id) {
        this.method = method
        this.inputForm.id = id
        if (method === 'add') {
          this.title = `新建商家商家信息`
        } else if (method === 'edit') {
          this.title = '修改商家商家信息'
        } else if (method === 'view') {
          this.title = '查看商家商家信息'
        }
        this.pictureArra = []
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/common_eventmerchants/commonEventMerchants/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.commonEventMerchants)
              this.initMap(this.inputForm.longitude, this.inputForm.latitude);
              this.inputForm.picture.split('|').forEach((item) => {
                if (item.trim().length > 0) {
                  this.pictureArra.push({name: decodeURIComponent(item.substring(item.lastIndexOf('/') + 1)), url: item})
                }
              })
              this.loading = false
            })
          }else {
          this.initMap();
        }
        })
      },
      initMap(longitude, latitude) {
      var that = this;
      let address = "";
      let lat = "36.752508224779746";
      let logt = "119.97121810913086";
      if (!longitude) {
        let lat = latitude;
        let logt = longitude;
      }
      if (this.inputForm.latitude === "") {
        var center = new qq.maps.LatLng(lat, logt);
      } else {
        var center = new qq.maps.LatLng(
          this.inputForm.latitude,
          this.inputForm.longitude
        );
      }
      var map = new qq.maps.Map(document.getElementById("containepic"), {
        center: center,
        zoom: 13,
        disableDefaultUI: true,
      });
      var marker = new qq.maps.Marker({
        position: center,
        map: map,
      });
      that.markersArray.push(marker);
      var infoWin = new qq.maps.InfoWindow({
        map: map,
      }); //此处是点击地图后生成的地标名称
      var geocoder = new qq.maps.Geocoder({
        complete: function (res) {
          that.deleteOverlays();
          map.setCenter(res.detail.location);
          var marker = new qq.maps.Marker({
            map: map,
            position: res.detail.location,
          });
          that.markersArray.push(marker);
        },
      });

      qq.maps.event.addListener(map, "click", function (event) {
        that.deleteOverlays();
        // this.latitude = event.latLng.getLat();
        // this.longiistude = event.latLng.getLng();
        // console.log(this.longiistude, this.latitude);
        that.inputForm.longitude = event.latLng.getLng();
        that.inputForm.latitude = event.latLng.getLat();
        var position = new qq.maps.LatLng(
          that.inputForm.latitude,
          that.inputForm.longitude
        );
        var marker = new qq.maps.Marker({
          map: map,
          position: position,
        });
        that.markersArray.push(marker);
      });
      document
        .getElementById("handleinput")
        .addEventListener("blur", function () {
          console.log("1111");
          geocoder.getLocation(that.inputForm.address);
        });
    },
    deleteOverlays() {
      if (this.markersArray) {
        for (var i in this.markersArray) {
          this.markersArray[i].setMap(null);
        }
        this.markersArray.length = 0;
      }
    },
   
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/common_eventmerchants/commonEventMerchants/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              this.loading = false
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
            })
          }
        })
      }
    }
  }
</script>
<style lang="less">
  #containepic {
    width: 750px;
    height: 500px;
  }
  </style>
  